<?php
namespace Admin\Controller;
use Think\Page;
use Admin\Model\UserModel;
use Admin\Model\CommonModel;
use Admin\Model\ShareModel;
use Think\Snoopy;
class UserController extends BaseController{
	//会员列表
	public function index(){
		
		//分页相关开始
		$model=new UserModel();
		$common=new CommonModel();
		$listRows=10;												//每页记录数
		$sort=I('get.sortT') ? I('get.sortT') :'';
		$user=I('get.user') ? I('get.user') : '';
		$w['status']=0;
		if ($user) {
			$w['name']=array('like','%'.$user.'%');
			$totalRows=$common->count('user',$w);
		}else {
			$totalRows=$common->count('user',$w);
		}
		$pn=I('get.p') ? I('get.p'):1;								//第几页.无页码是默认第一页
		if (!is_numeric($pn)) $this->error('页码参数错误，必须为数字！');	//容错机制
		$data=$model->get_users($pn,$listRows,$sort,$user);						//按页获取记录
		$page=new Page($totalRows,$listRows);
		$show=$page->show();
// 		print_r($data);die();
		$this->assign('data',$data);
		$this->assign('page',$show);
		$this->assign('title','会员管理');
		$this->display();
	}
	
	
	//收录会员
	public function collect(){
		if (IS_POST){
			$model=new UserModel();
			$uk=$model->collect_uk(I('post.content'));
			for ($i=0;$i<count($uk);$i++){
				if ($model->check_uk($uk[$i])==0) {//如果在数据库未存在，则收录，否则不再收录
					$data=$model->get_user_info($uk[$i]);
					if (is_object($data) && $data->errno==0) {
						$arr[$i]=$data->user_info;
					}else{
						$fail[]=$uk[$i];
					}
				}
			}
			$model->addAllUserInfo($arr);
			//如果存在cookie，则表示有部分收录失败
			if (is_array($fail)) {
				cookie('uk',$fail);
				$this->redirect('User/fail');
			}else {
				$this->success('恭喜您，全部收录成功！【提示：如果该会员之前已被添加过，系统将不会重复添加】');
			}
		}
	}
	
	//此处待完善
	public function fail(){
		echo "添加失败的会员，请重试或者使用手动添加的方式进行添加";
		print_r($_COOKIE['uk']);
		die();
		
	}
	
	//采集会员资源的操作
	public function collect_source(){
		set_time_limit(120);
		header("Content-type: text/html; charset=utf-8"); 
		unset($_SESSION['__hash__']);
// 		print_r($_SESSION);
		$share=new ShareModel();
		$total=I('get.shareNum');//分享数量
		$uk=I('get.uk');//分享会员的UK
		$pn=I('get.pn') ? I('get.pn'):1;//采集页数
		$limt=60;
		$totalpage=ceil($total/$limt);//总页数
		$start=($pn-1)*$limt;//从第几条记录开始
		echo "<div style='width:100%;line-height:500%;text-align:center;'>本次采集共分为".$totalpage."页，当前正在采集第".$pn."页...</div>";
		$rs=$share->get_source($uk, $start,$limt,$total);
		if ($rs==1){
			$pn++;
		}else{
			$randSecond=rand(2,3);
			$this->error('没采集到，再来一次..',U('User/collect_source',array('uk'=>$uk,'shareNum'=>$total,'pn'=>$pn)),$randSecond);
// 			$this->error('采集失败，请重试，或者使用手动式采集');
		}
		if ($pn>$totalpage) {
			$user=M('user');
			//采集小于1860个的资源
			$user->where(array('uk'=>$uk))->save(array('status'=>1));
			
			$d=$user->where(array('status'=>0,'share'=>array('lt',1861)))->order('share desc')->find();
// 			$d=$user->where(array('status'=>0))->order('share desc')->find();
			//http://baiduyun.57fx.cn/Admin-User-collect_source.html?uk=2500327416&shareNum=642
			$s_n=$d['share']+$d['album'];
			$this->success('恭喜您，成功采集完毕，5秒钟后跳转，如需停止采集，请关闭当前页面..',U('User/collect_source',array('uk'=>$d['uk'],'shareNum'=>$s_n)),2);
			die();
		}
		$params=array(
				'shareNum'=>$total,
				'uk'=>$uk,
				'pn'=>$pn
		);
		$randSecond=rand(3, 5);
		$this->redirect('User/collect_source',$params,$randSecond,'<div style="width:100%;line-height:500%;text-align:center;">程序正在采集中，请勿关闭当前页面...'.$randSecond.'秒后跳转</div>');
	}
	
	//采集订阅
	public function collect_follow(){
		header("Content-type: text/html; charset=utf-8");
		$user=new UserModel();
		$total=I('get.followNum');//订阅数量
		$uk=I('get.uk');//分享会员的UK
		$pn=I('get.pn') ? I('get.pn'):1;//采集页数
		$limt=24;
		$totalpage=ceil($total/$limt);//总页数
		$start=($pn-1)*$limt;//从第几条记录开始
		echo "<div style='width:100%;line-height:500%;text-align:center;'>本次采集共分为".$totalpage."页，当前正在采集第".$pn."页...</div>";
		try {
			$rs=$user->getFollow($uk, $start,$limt);
		} catch (\Exception $e) {
			$this->error($e->getMessage().'!重试！',U('collect_follow',array('uk'=>$uk,'pn'=>($pn-1),'total'=>$total)));
		}
		
		if ($start>$total) {
			$user->where(array('uk'=>$uk))->save(array('is_follow'=>1));
			$d=$user->where(array('is_follow'=>0,'follow'=>array('gt',0)))->order('rand()')->find();
			$this->success('恭喜您，采集完毕，还有5秒跳转采集下一个分享达人的订阅。。如需停止采集，请手动关闭当前页面..',U('User/collect_follow',array('uk'=>$d['uk'],'followNum'=>$d['follow'])),5);
			die();
		}
		$pn++;
// 		$msg="Divided into ".$totalpage."pages in total to collect，the Num".($pn-1)." page is collected，and we come to collect Num ".$pn." page..";
		$params=array(
				'followNum'=>$total,
				'uk'=>$uk,
				'pn'=>$pn
		);
		$this->redirect('User/collect_follow',$params,rand(3,5),'<div style="width:100%;line-height:500%;text-align:center;">程序正在采集中，请勿关闭当前页面...</div>');
	}
	
	//多线程采集订阅
	public function muti_collect_follow(){
		header("Content-type: text/html; charset=utf-8");
		$user=new UserModel();
		$total=I('get.followNum');//订阅数量
		$uk=I('get.uk');//分享会员的UK
		$batch=I('get.batch') ? I('get.batch'):1;//采集批次
		$limt=24;
		$thread=I('get.thread') ? I('get.thread'):10;//线程数量
		$totalpage=ceil($total/$limt);//总页数,一页一个线程
		$totalBatch=ceil($totalpage/$thread);//总批次
		
		$index=$thread;
		$totalpage%$thread;
		if ($batch==$totalBatch) {
			$index=$totalpage%$thread;
		}
		
// 		echo $index;die();
		for ($i = 0; $i < $index; $i++) {
			$istart=$limt*$i+($batch-1)*$limt*$thread;
			$url_arr[$i]='http://yun.baidu.com/pcloud/friend/getfollowlist?query_uk='.$uk.'&limit='.$limt.'&start='.$istart.'&bdstoken=3afc5bc1d59fe96ef24dfceb33fe70d2&channel=chunlei&clienttype=0&web=1';
		}
// 		print_r($url_arr);
// 		die();
		
		echo "<div style='width:100%;line-height:500%;text-align:center;'>本次采集共分为".$totalBatch."批次，每批次".$thread."线程,当前正在采集第".$batch."批次...</div>";
		if ($batch>6 || $batch>$totalBatch) {//到7就无法再继续采集了
			$user->where(array('uk'=>$uk))->save(array('is_follow'=>1));
			$d=$user->where(array('is_follow'=>0,'follow'=>array('gt',24)))->order('rand()')->find();
			$this->success('恭喜您，采集完毕，还有5秒跳转采集下一个分享达人的订阅。。如需停止采集，请手动关闭当前页面..',U('User/muti_collect_follow',array('uk'=>$d['uk'],'followNum'=>$d['follow'])),5);
			die();
		}
		$rs=$user->getFollowMuti($url_arr, $uk);
		$batch++;
		$params=array(
				'followNum'=>$total,
				'uk'=>$uk,
				'batch'=>$batch,
				'thread'=>$thread
		);
		$this->redirect('User/muti_collect_follow',$params,rand(3,5),'<div style="width:100%;line-height:500%;text-align:center;">程序正在采集中，请勿关闭当前页面...</div>');
	}
	
	//采集粉丝
	public function collect_fans(){
		header("Content-type: text/html; charset=utf-8");
		$user=new UserModel();
		$total=I('get.fansNum');//分享数量
		$uk=I('get.uk');//分享会员的UK
		$pn=I('get.pn') ? I('get.pn'):1;//采集页数
		$limt=24;
		$totalpage=ceil($total/$limt);//总页数
		$start=($pn-1)*$limt;//从第几条记录开始
		echo "<div style='width:100%;line-height:500%;text-align:center;'>本次采集共分为".$totalpage."页，当前正在采集第".$pn."页...</div>";
		$rs=$user->getFans($uk, $start,$limt);
		$pn++;
		if ($pn>$totalpage || $pn>100) {
			$this->success('恭喜您，成功采集完毕，正在跳转..',U('User/index'));
		}
		$params=array(
				'fansNum'=>$total,
				'uk'=>$uk,
				'pn'=>$pn
		);
		$delay=1;
		$this->redirect('User/collect_fans',$params,rand(3,5),'<div style="width:100%;line-height:500%;text-align:center;">程序正在采集中，请勿关闭当前页面...</div>');
	}
	
	
	 
	public function collect_code(){
		if (IS_POST) {
			$user=new UserModel();
			$user->preg_header(I('post.content_code'))==1 ? $this->success('采集成功！',U('User/index')) : $this->error('采集失败，可能是数据库已存在该会员信息！');
		}
	}
	
	//设置会员状态
	public function recommend(){
			$user=new UserModel();
			$user->set_recommend(I('get.uk'), I('get.recommend'))==1 ? $this->success('状态设置成功！') : $this->error('状态设置失败，请刷新页面后再重试');
		
	}
	
	//更新会员信息
	public function update(){
		$user=new UserModel();
		$rs=$user->update(I('get.uk'));
		switch ($rs){
			case -1:
				$this->error('无法抓取百度网盘会员信息，会员信息更新失败，请检查网络是否通畅。');
				break;
			case 0:
				$this->error('该会员信息目前暂时没有变动，无需更新。');
				break;
			case 1:
				$this->success('会员信息更新成功。');
				break;
		}
	}
	
	//json形式收录资源
	public function collect_json(){
		$content=$_POST['content_json'];
		$share=new ShareModel();
		echo $share->do_json($content);die();
	}
	
	//json形式收录会员
	public function collect_user_json(){
		$content=$_POST['user_json'];
		$share=new UserModel();
		echo $share->get_user_json($content);die();
	}
	
	//删除会员
	public function delete_user(){
		$w['uk']=I('get.uk');
		if ($w['uk']) {
			M('user')->where($w)->delete();
			M('share')->where($w)->delete();
			M('user')->where($w)->delete();
			M('album')->where($w)->delete();
			M('album_source')->where($w)->delete();
			$this->success('会员删除成功！');
		}else{
			$this->error('会员删除失败！');
		}
	}
	
	//采集手机订阅
	public function snoopy_wapFollows(){
		set_time_limit(300);
		$snoopy=new Snoopy();
		$followNum=I('get.followNum');
		$uk=I('get.uk');
		$pn=I('get.pn') ? I('get.pn'):1;
		$start=($pn-1)*20;
		$User=new UserModel();
		try {
			$User->preg_wapFollows($uk, $start);
		} catch (\Exception $e) {
			$this->error($e->getMessage().'||重试！',U('snoopy_wapFollows'));
		}
		if ($start<$followNum) {
			echo $pn.'采集完毕，正在进入下一页采集。';
			$this->redirect('User/snoopy_wapFollows',array('uk'=>$uk,'pn'=>($pn+1),'followNum'=>$followNum),1);
		}else{
			$User->where(array('uk'=>$uk))->save(array('is_follow'=>1));
			$d=$User->where(array('is_follow'=>0,'follow'=>array('gt',0)))->order('rand()')->find();
			$d ? '' : die('nothing');
			$this->success('恭喜您，采集完毕，还有5秒跳转采集下一个分享达人的订阅。。如需停止采集，请手动关闭当前页面..',U('User/snoopy_wapFollows',array('uk'=>$d['uk'],'followNum'=>$d['follow'])),2);
			die();
		}
	}
	
	
	//采集手机订阅
	public function snoopy_wapFans(){
		$snoopy=new Snoopy();
		$fansNum=I('get.fansNum');
		$uk=I('get.uk');
		$pn=I('get.pn') ? I('get.pn'):1;
		$start=($pn-1)*20;
		$User=new UserModel();
		$User->preg_wapFollows($uk,$start,$fans=1);
		if ($start<$fansNum) {
			echo $pn.'采集完毕，正在进入下一页采集。';
			$this->redirect('User/snoopy_wapFans',array('uk'=>$uk,'pn'=>($pn+1),'followNum'=>$followNum),1);
		}else{
			$User->where(array('uk'=>$uk))->save(array('is_fans'=>1));
			$d=$User->where(array('is_fans'=>0,'fans'=>array('gt',0)))->order('rand()')->find();
			$d ? '' : die('nothing');
			$this->success('恭喜您，采集完毕，还有5秒跳转采集下一个分享达人的订阅。。如需停止采集，请手动关闭当前页面..',U('User/snoopy_wapFans',array('uk'=>$d['uk'],'fansNum'=>$d['fans'])),2);
			die();
		}
	}
	
	//从hc_wap表中
	//http://pan.baidu.com/pcloud/user/getinfo?bdstoken=6a6bf18b3c48ad316d679135bcdbd7f3&query_uk=2031761197&t=1429708064749&channel=chunlei&clienttype=0&web=1
	
	public function get_user_info_by_wap(){
		set_time_limit(300);
		$User=new UserModel();
		$Wap=M('wap');
		$data=$Wap->where(array('isfollow'=>0))->limit(20)->select();
		if(!$data) die('finished');
// 		print_r($data);
// 		$data　? '' : die('OMG,nothing');
		for($i=0;$i<count($data);$i++){
			$url[]='http://pan.baidu.com/pcloud/user/getinfo?bdstoken=6a6bf18b3c48ad316d679135bcdbd7f3&query_uk='.$data[$i]['uk'].'&t=1429708064749&channel=chunlei&clienttype=0&web=1';
		}
		$rs=$User->getMutiUserInfo($url);
// 		$rs=$User->getMutiUserInfo2($url);
		if ($rs) {
			if (is_array($rs)) {
				for($i=0;$i<count($rs);$i++){
					$uks.=$data[$i]['uk'].',';
				}
				$uks=rtrim($uks,',');
				$Wap->where(array('uk'=>array('in',$uks)))->save(array('isfollow'=>1));
			}
			$this->success('进入下一次采集.TIME:'.date('Y-m-d H:i:s'),U('User/get_user_info_by_wap'),rand(1, 5));
		}else{
			$second=rand(10, 15);
			$this->error($second.'秒钟之后刷新一次当前页面',U('User/get_user_info_by_wap'),$second);
		}
		
	}
	
	public function get_user_info_by_preg(){
		$User=new UserModel();
		$Wap=M('wap');
		$data=$Wap->where(array('isfollow'=>0))->limit(10)->select();
		for($i=0;$i<count($data);$i++){
			$ids.=$data[$i]['id'].',';
			$User->getMutiUserInfo2($data[$i]['uk']);
		}
		$ids=rtrim($ids,',');
		$Wap->where(array('id'=>array('in',$ids)))->save(array('isfollow'=>1));
		$this->success('进入下一次采集.TIME:'.date('Y-m-d H:i:s'),U('User/get_user_info_by_preg'),rand(3, 5));
		
	}
	
	
	public function attach(){
		$User=new UserModel();
		$arr=array();
		for ($i=0;$i<10;$i++){
// 			$arr[$i]='http://www.jc0531.com/effect/source/bg/1381564335';
// 			$arr[$i]='http://www.yunpan11.com/js/23.jpg';
			$arr[$i]='http://www.yunpan11.com/js/1111111.jpg';
		}
		$User->attackYunpan11($arr);
		$this->success('成功，再来一次！',U('User/attach'),1);
	}
	
	
	//采集会员资源的操作
	public function collect_html(){
		set_time_limit(0);
		header("Content-type: text/html; charset=utf-8");
		print_r($_SESSION);
		$share=new ShareModel();
		$total=I('get.shareNum');//分享数量
		$uk=I('get.uk') ? I('get.uk') : '2920788743';//分享会员的UK
		$pn=I('get.pn') ? I('get.pn'):1;//采集页数
		$limt=20;
		$totalpage=ceil($total/$limt);//总页数
		$start=($pn-1)*$limt;//从第几条记录开始
		echo "<div style='width:100%;line-height:500%;text-align:center;'>本次采集共分为".$totalpage."页，当前正在采集第".$pn."页...</div>";
		echo $url='http://pan.baidu.com/wap/share/home?third=0&uk='.$uk.'&start='.$start;
		//http://pan.baidu.com/wap/share/home?third=0&uk=3124509720&start=0
		$html=file_get_contents($url);
		$rs=file_put_contents('./html/'.$uk.'_'.$pn.'.html', $html);
		if ($rs){
			$pn++;
		}else{
			$this->error('采集失败，请重试，或者使用手动式采集');
		}
		if ($pn>$totalpage) {
			$user=M('user');
			$user->where(array('uk'=>$uk))->save(array('is_html'=>1));
			$d=$user->where(array('is_html'=>0))->order('share desc')->find();
			//http://baiduyun.57fx.cn/Admin-User-collect_source.html?uk=2500327416&shareNum=642
			$s_n=$d['share']+$d['album'];
			$this->success('恭喜您，成功采集完毕，5秒钟后跳转，如需停止采集，请关闭当前页面..',U('User/collect_html',array('uk'=>$d['uk'],'shareNum'=>$s_n)),5);
			die();
		}
		$params=array(
				'shareNum'=>$total,
				'uk'=>$uk,
				'pn'=>$pn
		);
		$randSecond=rand(2, 4);
		$this->redirect('User/collect_html',$params,$randSecond,'<div style="width:100%;line-height:500%;text-align:center;">程序正在采集中，请勿关闭当前页面...'.$randSecond.'秒后跳转</div>');
	}
	
	
	public function wap2html(){
		$Wap=M('wap');
		$data=$Wap->where(array('isfollow'=>0))->field('uk')->limit(1000)->order('id desc')->select();
		foreach ($data as $v){
			echo 'http://yun.baidu.com/pcloud/user/getinfo?bdstoken=53331ce564a5c5877066e18c033f55df&query_uk='.$v['uk'].'&t=1436445799370&channel=chunlei&clienttype=0&web=1<br/>';
		}
	}
	
	
	public function updateDoctype(){
		$Model=M('share1');
		$pn=I('get.pn') ? I('get.pn') : 1;
		$limit=1000;
		$data=$Model->limit(($pn-1)*$limit,$limit)->field('id,doctype')->select();
		$data ? '' : $this->success('全部完毕',U('User/index'));
		foreach ($data as $v){
			$v['type']=doctype2type($v['doctype']);
			$Model->save($v);
		}
		$this->success('更新成功，继续下一页',U('User/updateDoctype',array('pn'=>($pn+1))));
	}
	/**
	 * 多线程采集资源  */
	public function multiple_source(){
		set_time_limit(300);
		$thread=I('get.thread',20);
		$thread||$thread=20;
		$UserModel=new UserModel();
		$UserModel->multiple($thread);
		$this->success('多线程采集成功，继续采集'.date('Y-m-d H:i:s'),U('multiple_source',array('thread'=>$thread)),rand(5, 8));
	}
	
	
	
}